package com.zy.chapter8

import java.util.Date

import scala.collection.mutable.ArrayBuffer

/**
 * @author: zhaoyi
 * @create: 2020-08-02 18:08
 * @description: 类型检查和转换
 **/
object CheckType extends App {

  val emp = new Employee("zs", 1)
  val emp2 = new Employee("zs", 1, 2)
  val per = new Person("zs")
  val nan = null

  println(emp.age)
  println(emp2.age)


  println(per.age)


  //Person或者其子类  isInstanceOf[Person] 都返回true
  println(emp.isInstanceOf[Person]) //true
  println(per.isInstanceOf[Person]) //true

  println(per.getClass == classOf[Person]) //true
  println(emp.getClass == classOf[Person]) //false

  println(per.getClass eq classOf[Person]) //true


  who(per)
  who(emp2)
  who(nan)

  def who(obj: Any): Unit = {
    //存在继承关系时子类放前面
    obj match {
      //case p : Person => println(s"is person $p") //如果把父类放前面 都会先匹配上父类
      case e: Employee => println(s"is employ $e")
      case p: Person => println(s"is person $p")
      case _ => println(s"is others $obj")
    }
  }



  println(per.isInstanceOf[Employee]) //false
  println(per.isInstanceOf[Person])


  println(emp.asInstanceOf[Person].name)//子类可以转换成父类
  //println(per.asInstanceOf[Employee].name) //Exception 父类不能转换成子类
  println(per.asInstanceOf[Person].name)

  println(nan.asInstanceOf[Person]) //null转换成任何类型 (不会异常) 都还是null

  println(emp.asInstanceOf[Employee])



}
